<?php


namespace app\admin\controller\cla;

use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use jianyan\excel\Excel;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\App;
use think\facade\Db;

/**
 * @ControllerAnnotation(title="分类")
 */
class Classification extends AdminController
{

    use \app\admin\traits\Curd;
    protected $sort = [
        'sort'   => 'asc',
    ];

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new \app\admin\model\Classification();
        
    }
    
    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            list($page, $limit, $where) = $this->buildTableParames();
            $count = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }


    /**
    * @NodeAnotation(title="添加")
    */
    public function add()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->param();
            if(empty($post['title'])){
                $this->error('分类名称不能为空');
            }
            $data = [
                'title'=>$post['title'],
                'img'=>$post['image'],
                'create_time'=>time()
            ];
            try {
                $save = $this->model->save($data);
            } catch (\Exception $e) {
                $this->error('保存失败:' . $e->getMessage());
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        return $this->fetch();
        // //根据物料编码查询类型匹配 401,450
        //  $wlbm = Db::name("wlbm")->whereBetween('id','1,50')->order("id asc")->select();
        //  ini_set('max_execution_time', '0');
        //  foreach($wlbm as $k=>$v){
        //     $crm_code = $this->gl_phone_customer($v["code"]); 
        //         //存货类别名称
        //         if($crm_code == "56Kxvrw5c"){
        //             $name = "水电人工费";
        //         }elseif($crm_code == "3x5UdAguf"){
        //             $name = "木工人工费";
        //         }elseif($crm_code == "F5iA3W1n3"){
        //             $name = "瓦工人工费";
        //         }elseif($crm_code == "43a928B9u"){
        //             $name = "油工人工费";
        //         }elseif($crm_code == "5lU2w9RDm"){
        //             $name = "拆除人工费";
        //         }elseif($crm_code == "pEDr2Y9D1"){
        //             $name = "瓷砖加工工费";
        //         }elseif($crm_code == "n92fZL0rS"){
        //             $name = "垃圾外运人工费";
        //         }elseif($crm_code == "1rgg36tru"){
        //             $name = "新建人工费";
        //         }elseif($crm_code == "56cMcnQoV"){
        //             $name = "形象保护人工费";
        //         }elseif($crm_code == "13g3894l5"){
        //             $name = "分包费";
        //         }elseif($crm_code == "esjoPee37"){
        //             $name = "电器安装人工费";
        //         }elseif($crm_code == "ubQ51mNbW"){
        //             $name = "家具安装人工费";
        //         }elseif($crm_code == "1Qf20X0j5"){
        //             $name = "软装安装人工费";
        //         }elseif($crm_code == "K582bVuWy"){
        //             $name = "衣柜安装人工费";
        //         }elseif($crm_code == "j03pG6arW"){
        //             $name = "橱柜安装人工费";
        //         }elseif($crm_code == "2y7um7q9t"){
        //             $name = "室内门安装人工费";
        //         }elseif($crm_code == "Rg1BMr9aw"){
        //             $name = "卫浴安装人工费";
        //         }elseif($crm_code == "588OQEk6c"){
        //             $name = "工人拣货费";
        //         }
        //         elseif($crm_code == "bJNOEnp6z"){
        //             $name = "水电材料";
        //         }
        //         elseif($crm_code == "2KSGIrcjw"){$name = "木工材料";}
        //         elseif($crm_code == "24s2d1OEs"){$name = "瓦工材料";}
        //         elseif($crm_code == "2zySf6rJa"){$name = "油工材料";}
        //         elseif($crm_code == "NZ8ArnGRj"){$name = "新建材料";}
        //         elseif($crm_code == "kw1B0fa07"){$name = "形象保护材料";}
        //         elseif($crm_code == "wtCdG9DoZ"){$name = "电器材料成本";}
        //         elseif($crm_code == "s16ONZ3DO"){$name = "家具材料成本";}
        //         elseif($crm_code == "1C477yp1Z"){$name = "软装材料成本";}
        //         elseif($crm_code == "y0F56800E"){$name = "木地板材料费";}
        //         elseif($crm_code == "y3tO1uhwF"){$name = "衣柜材料成本";}
        //         elseif($crm_code == "sf9lf614S"){$name = "橱柜材料成本";}
        //         elseif($crm_code == "W1TvTyOQ7"){$name = "室内门材料成本";}
        //         elseif($crm_code == "A7ijgl26C"){$name = "卫浴材料成本";}
        //         elseif($crm_code == "i691q8ru3"){$name = "瓷砖材料成本";}
        //         elseif($crm_code == "9s5T58qN0"){$name = "长运";}
        //         elseif($crm_code == "qb24rj817"){$name = "短运";}
        //         elseif($crm_code == "5306zaKoc"){$name = "上楼费";}
        //         elseif($crm_code == "2j4i9btva"){$name = "远程费";}
        //         elseif($crm_code == "J1Y0hk5Oy"){$name = "开工/竣工成本";}
        //         elseif($crm_code == "kn1eopG91"){
        //             $name = "售后费";
        //         }else{
        //             $name = "";
        //         }

        //         //存货类别编码
        //         if($name == "水电人工费"){
        //             $chbm = "CHLB.001";
        //         }elseif($name == "木工人工费"){$chbm = "CHLB.002";}
        //         elseif($name == "瓦工人工费"){$chbm = "CHLB.003";}
        //         elseif($name == "油工人工费"){$chbm = "CHLB.004";}
        //         elseif($name == "拆除人工费"){$chbm = "CHLB.005";}
        //         elseif($name == "瓷砖加工工费"){$chbm = "CHLB.006";}
        //         elseif($name == "垃圾外运人工费"){$chbm = "CHLB.007";}
        //         elseif($name == "新建人工费"){$chbm = "CHLB.008";}
        //         elseif($name == "形象保护人工费"){$chbm = "CHLB.009";}
        //         elseif($name == "分包费"){$chbm = "CHLB.010";}
        //         elseif($name == "电器安装人工费"){$chbm = "CHLB.011";}
        //         elseif($name == "家具安装人工费"){$chbm = "CHLB.012";}
        //         elseif($name == "软装安装人工费"){$chbm = "CHLB.013";}
        //         elseif($name == "衣柜安装人工费"){$chbm = "CHLB.014";}
        //         elseif($name == "橱柜安装人工费"){$chbm = "CHLB.015";}
        //         elseif($name == "室内门安装人工费"){$chbm = "CHLB.016";}
        //         elseif($name == "卫浴安装人工费"){$chbm = "CHLB.017";}
        //         elseif($name == "水电材料"){$chbm = "CHLB.018";}
        //         elseif($name == "木工材料"){$chbm = "CHLB.019";}
        //         elseif($name == "瓦工材料"){$chbm = "CHLB.020";}
        //         elseif($name == "油工材料"){$chbm = "CHLB.021";}
        //         elseif($name == "新建材料"){$chbm = "CHLB.022";}
        //         elseif($name == "形象保护材料"){$chbm = "CHLB.023";}
        //         elseif($name == "电器材料成本"){$chbm = "CHLB.024";}
        //         elseif($name == "家具材料成本"){$chbm = "CHLB.025";}
        //         elseif($name == "软装材料成本"){$chbm = "CHLB.026";}
        //         elseif($name == "衣柜材料成本"){$chbm = "CHLB.027";}
        //         elseif($name == "橱柜材料成本"){$chbm = "CHLB.028";}
        //         elseif($name == "室内门材料成本"){$chbm = "CHLB.029";}
        //         elseif($name == "卫浴材料成本"){$chbm = "CHLB.030";}
        //         elseif($name == "瓷砖材料成本"){$chbm = "CHLB.031";}
        //         elseif($name == "长运"){$chbm = "CHLB.032";}
        //         elseif($name == "短运"){$chbm = "CHLB.033";}
        //         elseif($name == "上楼费"){$chbm = "CHLB.034";}
        //         elseif($name == "远程费"){$chbm = "CHLB.035";}
        //         elseif($name == "开工/竣工成本"){
        //             $chbm = "CHLB.036";
        //         }else{
        //             $chbm = "";
        //         } 
        //         Db::name("wlbm")->where("code",$v["code"])->update([
        //             "name"=>$name,
        //             "crm_code"=>$chbm
        //         ]); 
        //  }
        //  dump(1);die;
      
     
    }

    /**
    * @NodeAnotation(title="导出")
    */
    public function export()
    {
    //学生组（个人） 奖项主题  主创姓名 报名日期  参赛分类 报名审核状态 审核意见 作品类别 指导老师 指导老师性别 指导老师职称 指导老师联系方式 指导老师邮箱 指导老师通讯地址 备注
    //学生组（团体） 奖项主题  主创姓名 团队成员  报名日期  参赛分类  报名审核状态  审核意见 作品类别 指导老师 指导老师性别 指导老师职称 指导老师联系方式 指导老师邮箱 指导老师通讯地址 备注
         
        //查询数据
        $list = Db::name("wlbm")->whereBetween('id','1,10')->order("id asc")->select();

        $list = $list->toArray();
      
        $data_h = [
            ['物料编码','code'],
            ['存货类别名称','name'],
            ['存货类别编码','crm_code'],
         
        ];
        $arr = [];
        foreach($list as $k=>$v){
            $arr[$k]['code'] = $v['code'];
            $arr[$k]['name'] = $v['name'];
            $arr[$k]['crm_code'] = $v['crm_code'];
     
        }
        $fileName = time()."物料编码表";
            
        return Excel::exportData($arr, $data_h, $fileName, 'xlsx');
    }
  

     /**
    * @NodeAnotation(title="编辑")
    */
    public function edit()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->param();
            if(empty($post['title'])){
                $this->error('分类名称不能为空');
            }
            $data = [
                'title'=>$post['title'],
                'img'=>$post['image']
            ];
            try {
               $this->model->where('id',$post['id'])->update($data);
            } catch (\Exception $e) {
                $this->error('保存失败:' . $e->getMessage());
            }
            $this->success('保存成功') ;
        }else{
            $post = $this->request->param(); 
            $row = $this->model->where('id',$post['id'])->find();
            $this->assign('row', $row);
        }
        return $this->fetch();
    }

     //查询手机号关联客户
     public function gl_phone_customer($code){
       // $code = "CS.01.CL.000002";
        $qwe = $this->corpAccessToken();
        $url = 'https://open.fxiaoke.com/cgi/crm/custom/v2/data/query';
        $corpAccessToken = $qwe['corpAccessToken'];   
        $corpId = $qwe['corpId'];
        $currentOpenUserId = 'FSUID_B9743F457C3ABD3C3FA9473741D905DE';
        $data = [ 'search_query_info'=>[ 'offset'=>0, 'limit'=>100, 'filters'=>[[ 'field_name'=>'name','field_values'=>[$code],'operator'=>'EQ' ]]],'dataObjectApiName'=>'ProductObj'];
 
        $res =  json_encode(compact('corpAccessToken', 'corpId', 'currentOpenUserId', 'data'),JSON_UNESCAPED_UNICODE);
        //dump($res);die;
        $method = 'POST';
        $header = [
                       'Content-Type:application/json'
                   ];
        $dsdf = $this->http_curl($url,$method, $res, $header, $timeout = 10);
        if($dsdf['errorMessage'] == 'OK' && $dsdf['errorCode'] == 0){
            if(!empty($dsdf['data'])){
                if(!empty($dsdf["data"]["dataList"][0]["field_1m7l7__c"])){
                    return $dsdf["data"]["dataList"][0]["field_1m7l7__c"];
                }else{
                    return "";
                }
                
            }else{
                return "";
            }
            
        }else{
            return "";
        }
    }

     /**
    * 发送 post 请求 
    * @access protected
    * @return string
    */
    protected function http_curl($url, $method = 'POST', $data = array(), $header, $timeout = 10)
   {
       $curl = curl_init($url);
       $method = strtoupper($method);
       //请求方式啥
       curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
       //post请求
       if ($method == 'POST') curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
       //超时时间
       curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
       //设置header头
       // if ($header !== false) curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
       curl_setopt($curl, CURLOPT_HTTPHEADER, $header); 
       
       curl_setopt($curl, CURLOPT_FAILONERROR, false);
       //返回抓取数据
       curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
       //输出header头信息
       curl_setopt($curl, CURLOPT_HEADER, true);
       //TRUE 时追踪句柄的请求字符串，从 PHP 5.1.3 开始可用。这个很关键，就是允许你查看请求header
       curl_setopt($curl, CURLINFO_HEADER_OUT, true);


       //https请求
       if (1 == strpos("$" . $url, "https://")) {
           curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
           curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
       }
       $curlError = curl_error($curl);
       
       list($content, $status) = [curl_exec($curl), curl_getinfo($curl), curl_close($curl)];
       $status = $status;
       
       $headerStr = trim(substr($content, 0, $status['header_size']));
       $content = trim(substr($content, $status['header_size']));
       $cont = json_decode($content,true);
        
       //  $cont['headers'] =$headerStr;   //返回的头部信息去掉
        return $cont;

   }

      /**
     * 获取token
     */
    public function corpAccessToken()
    {
        $method = 'POST';
        // $appId = 'FSAID_131aba6';
        // $appSecret = '69a6c56e23234bc9b56992f1468d103a';
        // $permanentCode = 'F7BE99269E4BFC33400A92D039A3E28F';
        $appId = 'FSAID_131b260';
        $appSecret = 'bc3f3bd184c54895aca794db584f36fa';
        $permanentCode = 'C4E757336822DECDBBBB2C6117ABF449';
        $url = 'https://open.fxiaoke.com/cgi/corpAccessToken/get/V2';
        $header = [
                         'Content-Type:application/json'
                   ];
        $res =  json_encode(compact('appId', 'appSecret', 'permanentCode'));
        $data = $this->http_curl($url,$method, $res, $header, $timeout = 10); 
        return $data;
        // if(!empty($data) && isset($data) && $data['errorCode'] ==0 && $data['errorMessage'] == 'success' )
        // {
        //     $data['addtime'] = time();
        //     if(Db::name('atoken')->where('id',1)->find())
        //     {
        //        $zxc = Db::name('atoken')->where('id',1)->update($data);  
        //     }else{
        //        $zxc = Db::name('atoken')->insert($data);  
        //     }
        //    return $data;
        // }
        
    }

     /**
     * @NodeAnotation(title="导入")
     */
    public function importOrder()
    {
        if ($this->request->method() == 'POST') {
            $rst = $this->importExcel();
            if ($rst['code'] == 1) {
                $this->success($rst['msg']);
            } else {
                $this->error($rst['msg']);
            }
        }
        return $this->fetch();
    }

    public function importExcel()
    {
        // 获取表单上传文件
        $file[] = request()->file('file');
   
       
        try {
            // 使用验证器验证上传的文件
            $rst = validate(['file' => [
                // 限制文件大小(单位b)，这里限制为4M
                'fileSize' => 5 * 1024 * 1024,
                // 限制文件后缀，多个后缀以英文逗号分割
                'fileExt' => 'xls,xlsx',
                // 更多规则请看“上传验证”的规则，文档地址https://www.kancloud.cn/manual/thinkphp6_0/1037629#_444
            ]])->check(['file' => $file]);
            $savename = \think\facade\Filesystem::disk('public')->putFile('topic', $file[0]);
            $fileExtendName = substr(strrchr($savename, '.'), 1);
            // 有Xls和Xlsx格式两种
            if ($fileExtendName == 'xlsx') {
                $objReader = IOFactory::createReader('Xlsx');
            } else {
                $objReader = IOFactory::createReader('Xls');
            }
            $objReader->setReadDataOnly(true);
            // 读取文件，tp6默认上传的文件，在runtime的相应目录下，可根据实际情况自己更改
            $objPHPExcel = $objReader->load($savename);
            $sheet = $objPHPExcel->getSheet(0); //excel中的第一张sheet
            $highestRow = $sheet->getHighestRow(); // 取得总行数
            $highestColumn = $sheet->getHighestColumn(); // 取得总列数
            \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn);
            $lines = $highestRow - 1;
            if ($lines <= 0) {
                return ['code' => 0, 'msg' => '数据不能为空'];
            }
            if ($lines > 100) {
                // $this->error('数据不能为空');
                return ['code' => 0, 'msg' => '一次最多上传100条数据'];
            }
            //循环读取excel表格，整合成数组。如果是不指定key的二维，就用$data[i][j]表示。
           
            $s_data = [];
            for ($j = 1; $j <= $highestRow; $j++) {
                $s_data[$j] = [
                    'code' => trim($objPHPExcel->getActiveSheet()->getCell("A" . $j)->getValue()), //项目
          
                ];
            
            }
            // foreach($s_data as $k=>$v){
            //     if(!$v["order_no"]){//判断是否为空（false）
            //         unset($s_data[$k]);//删除
            //     }
            // }
            //dump($s_data);die;
            Db::startTrans();
            try {
                // $s_data 订单数据  2022111755565010147 
             
                foreach ($s_data as $k => $v) {
                    Db::name("wlbm")->insert($v);
                 
                }
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return ['code' => 0, 'msg' => $e->getMessage()];
            }
            Db::commit();
            return ['code' => 1, 'msg' => '导入成功'];
            // print_r($data);exit;
        } catch (\think\exception\ValidateException $e) {
            return ['code' => 0, 'msg' => $e->getMessage()];
        }
    }

    
 
} 